// arch-tag: 2dd2c7ae-7101-4a65-99b3-88ddb614fdcc
package de.yvert.jingle.tools;

import de.yvert.jingle.ToneMapper;
import de.yvert.jingle.hdr.HdrImage2D;
import de.yvert.jingle.ldr.LdrImage2D;

public class AverageToneMapper implements ToneMapper
{

private float map(float in)
{ return in > 1 ? 1 : in; }

public void map(HdrImage2D in, LdrImage2D out)
{
	float[] from = in.getData();
	byte[] to = out.getData();
	
	float avg = from[0];
	
	for (int offset = 1; offset < from.length; offset += 4)
	{
		avg += map(from[offset+0]);
		avg += map(from[offset+1]);
		avg += map(from[offset+2]);
	}
	
	avg /= in.getWidth()*in.getHeight();
	
//	System.out.println("Max brightness: "+max);
	
	float factor = 0.75f/avg;
	for (int offset = 0; offset < from.length; offset += 4)
	{
		to[offset+0] = LdrImage2D.clamp(factor*from[offset+0]);
		to[offset+1] = LdrImage2D.clamp(factor*from[offset+1]);
		to[offset+2] = LdrImage2D.clamp(factor*from[offset+2]);
	}
}

}
